
import {ImmerReducer,Effect} from 'umi'
import { fetchProduct } from '@/api'

export interface stateType{
    productList:object[] | [],
    err:string | null
}

export interface productModelType{
    namespace: string
    state:stateType
    reducers:{
        setProductList:ImmerReducer<stateType>,//ImmerReducer用来方便的更新状态
    }
    effects:{
        getProductList:Effect
    }
}

const ProductModel:productModelType = {
    namespace:"product" ,//命名空间
    state:{
        productList:[],
        err:null
    },
    reducers:{
        setProductList(state,action){
            state.productList=action.payload.data
            state.err=action.payload.err
        }
    },
    effects:{ //副作用，相当于vuex中的actions
        *getProductList({payload},{call,put}):any{
            // 获取数据
            yield new Promise((resolve,rejceyt)=>{
                setTimeout(()=>{
                    resolve(123)
                },2000)
            })
            try{
                 let res:any=yield call(fetchProduct)
                yield put ({type:'setProductList',payload:{data:res.data,err:null}})
            }catch(e:any){
                console.log(e)
                yield put ({type:'setProductList',payload:{data:[],err:e.toString()}})
            }
        }
    }
}
export default ProductModel